<template>
  <div class="new-products-container">
    <CommonHeader />
    <FloatingSidebar />
    <div class="content">
      <h2><el-icon><Timer /></el-icon> 新品上市</h2>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 商品列表 -->
      <el-row :gutter="20" v-else-if="products.length > 0">
        <el-col :span="6" v-for="product in products" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" class="product-card" @click="navigateToProduct(product.id)">
            <img :src="product.image" class="product-image" @error="handleImageError">
            <div class="product-info">
              <h3 class="product-name-card">{{ product.name }}</h3>
              <div class="price">¥{{ product.price }}</div>
              <div class="store-sales">
                <span class="store-name">{{ product.storeName }}</span>
                <span class="sales">月销 {{ product.sales }}</span>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                @click.stop="handleAddToCart(product)"
                :loading="addingToCart === product.id"
              >
                {{ addingToCart === product.id ? '添加中...' : '加入购物车' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无新品商品" />
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :default-page-size="12"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <CommonFooter />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { Timer } from '@element-plus/icons-vue'
import { getHomeProductService, productPageService } from '@/api/product.js'

const router = useRouter()
const cartStore = useCartStore()

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const products = ref([])
const allProducts = ref([]) // 存储所有商品数据
const loading = ref(false)
const addingToCart = ref(null)

// 获取新品商品
const getNewProducts = async () => {
  try {
    loading.value = true
    const type = 2 // 新品上市类型
    const isHome = false
    const result = await getHomeProductService(type, isHome)
    
    if (result.code === 200) {
      allProducts.value = result.data || []
      total.value = allProducts.value.length
      updateDisplayedProducts()
    } else {
      ElMessage.error(result.message || '获取新品商品失败')
    }
  } catch (error) {
    console.error('获取新品商品失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新显示的商品（前端分页）
const updateDisplayedProducts = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  products.value = allProducts.value.slice(startIndex, endIndex)
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  updateDisplayedProducts()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  updateDisplayedProducts()
}

// 跳转到商品详情
const navigateToProduct = (productId) => {
  router.push(`/home/product/${productId}`)
}

// 添加到购物车
const handleAddToCart = async (product) => {
  try {
    addingToCart.value = product.id
    cartStore.addToCart(product)
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加失败，请重试')
  } finally {
    addingToCart.value = null
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = '/src/assets/images/default.png' // 设置默认图片
}

// 页面加载时获取数据
onMounted(() => {
  getNewProducts()
})
</script>

<style scoped>
.new-products-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

h2 .el-icon {
  font-size: 24px;
  color: #409EFF;
}

.loading-container {
  padding: 20px 0;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.product-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  border-color: #409EFF;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  padding: 14px;
}

.product-name-card {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  line-height: 1.4;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.store-sales {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin: 8px 0 12px 0;
}

.store-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sales {
  margin-left: 10px;
  color: #67c23a;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    margin: 10px;
    padding: 15px;
  }
  
  .el-col {
    width: 100% !important;
  }
  
  h2 {
    font-size: 20px;
  }
  
  .product-image {
    height: 150px;
  }
}

@media (max-width: 1200px) {
  .el-col {
    width: 50% !important;
  }
}
</style> 